<template>
  <div class="statisticsContainer">
    <div class="statisticsTitle">
      <el-form class="form" :rules="rules" :inline="true" :model="chartData" ref="chartData">
        <el-form-item label="统计时段" prop="datetime">
          <el-date-picker v-model="chartData.datetime" type="datetimerange" range-separator="至" start-placeholder="开始时段" end-placeholder="结束时段" :picker-options="pickerOptions" size="small" value-format="yyyy-MM-dd HH:mm:ss" style="width:350px">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="路段">
          <el-select v-model="chartData.road" clearable size="small" placeholder="所有路段" :loading="addressLoading" loading-text="正在加载中..." no-data-text="暂无数据" @focus="handleRoadListFocus" style="width:190px">
            <el-option :label="addr" :value="addr" v-for="(addr,index) in address" :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="方式" prop="group">
          <el-select v-model="chartData.group" clearable size="small" placeholder="请选择" style="width:90px">
            <el-option :label="item.ch" :value="item.en" v-for="item in groups" :key="item.en">
              <span style="float: left;width:50px;display:block;">{{ item.ch }}</span>
              <span style="float: left; padding-left:20px; color: #c1cee0; font-size: 13px">{{ item.tip }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="handleClick" icon="el-icon-search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" size="small" @click="showchartsPdf=true" icon="el-icon-download">PDF</el-button>
        </el-form-item>
      </el-form>
    </div>
    <common-loading :loading="loading" loadingText="">
      <i slot="loadingIcon" class="el-icon-loading"></i>
    </common-loading>
    <div style="margin-left:20px;color:#fff;" v-show="!loading">{{tipforcharts}}</div>
    <div class="statisticsContent" id="statisticsContent" v-show="!loading">
      <div class="item" id="chart1">
        <div class="title">
          <div class="chartname" style="flex: 1;">行人入侵</div>
          <div class="el-icon-zoom-in" style="font-size: 20px;" @click="handleSize($event)" />
        </div>
        <div class="chart" id="people"></div>
      </div>
      <div class="item" id="chart2">
        <div class="title">
          <div class="chartname" style="flex: 1;">违规停车</div>
          <div class="el-icon-zoom-in" style="font-size: 20px;" @click="handleSize($event)" />
        </div>
        <div class="chart" id="stopping"></div>
      </div>
      <div class="item" id="chart3">
        <div class="title">
          <div class="chartname" style="flex: 1;">车辆拥堵</div>
          <div class="el-icon-zoom-in" style="font-size: 20px;" @click="handleSize($event)" />
        </div>
        <div class="chart" id="jam"></div>
      </div>
      <div class="item" id="chart4">
        <div class="title">
          <div class="chartname" style="flex: 1;">车流量统计</div>
          <div class="el-icon-zoom-in" style="font-size: 20px;" @click="handleSize($event)" />
        </div>
        <div class="chart" id="count"></div>
      </div>
      <div class="item" id="chart5">
        <div class="title">
          <div class="chartname" style="flex: 1;">路段流量统计</div>
          <div class="el-icon-zoom-in" style="font-size: 20px;" @click="handleSize($event)" />
        </div>
        <div class="chart" id="roadflow"></div>
      </div>
      <div class="item" id="chart6">
        <div class="title">
          <div class="chartname" style="flex: 1;">其他数据统计</div>
          <div class="el-icon-zoom-in" style="font-size: 20px;" @click="handleSize($event)" />
        </div>
        <div class="chart" id="other"></div>
      </div>
    </div>
    <el-dialog ref="dailog" :visible.sync="showchartsPdf" @opened="openPdf()" @close="handleDialogClose()" width="70%">
      <div slot="title" class="dialog-title">
        <span> PDF数据预览</span>
        <i slot="loadingIcon" class="el-icon-loading" v-if="!imgFlag"></i>
        <el-button icon='el-icon-download' @click="downloadPDF" circle size='mini' v-else />
      </div>
      <div class="pdfcon">
        <el-table :data="griddata" border style="font-size: 8px" class="pdftable" >
          <el-table-column property="index" :label="this.chartData.xname" min-width=5%></el-table-column>
          <el-table-column property="e_person" label="行人入侵" min-width=8%x></el-table-column>
          <el-table-column property="e_stop" label="违章停车" min-width=8%></el-table-column>
          <el-table-column property="e_jam" label="车辆拥堵" min-width=8%></el-table-column>
          <el-table-column property="count" label="总车流量" min-width=8%></el-table-column>
          <el-table-column property="upcount" label="上行车流量" min-width=10%></el-table-column>
          <el-table-column property="downcount" label="下行车流量" min-width=10%></el-table-column>
          <el-table-column property="road_flow" label="路段流量" min-width=9%></el-table-column>
          <!-- <el-table-column property="bdvehicle" label="危险品车辆" min-width=9%></el-table-column> -->
          <el-table-column property="e_back" label="逆行车辆" min-width=8%></el-table-column>
          <el-table-column property="e_dc" label="危险品车辆" min-width=10%></el-table-column>
          <el-table-column property="e_slow" label="缓行车辆" min-width=8%></el-table-column>
        </el-table>
        <div class="dialogchart" id='dialogchart1'>
          <div class="dtitle">行人入侵</div>
          <div class="dchart" id="dialogpeople"></div>
        </div>
        <div class="dialogchart" id='dialogchart2'>
          <div class="dtitle">违规停车</div>
          <div class="dchart" id="dialogstopping"></div>
        </div>
        <div class="dialogchart" id='dialogchart3'>
          <div class="dtitle">车辆拥堵</div>
          <div class="dchart" id="dialogjam"></div>
        </div>
        <div class="dialogchart" id='dialogchart4'>
          <div class="dtitle">车流量统计</div>
          <div class="dchart" id="dialogcount"></div>
        </div>
        <div class="dialogchart" id='dialogchart5'>
          <div class="dtitle">路段流量统计</div>
          <div class="dchart" id="dialogroadflow"></div>
        </div>
        <div class="dialogchart" id='dialogchart6'>
          <div class="dtitle">其他数据统计</div>
          <div class="dchart" id="dialogother"></div>
        </div>
        <div>
          <el-button size="small"  @click="handleDialogClose()" icon="el-icon-cancel">取消下载</el-button>
          <el-button type="primary" size="small" icon='el-icon-download' @click="downloadPDF" v-if="imgFlag" >下载pdf</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import echarts from 'echarts'
import _ from 'lodash'
import CommonLoading from "../components/CommonLoading.vue"
import jspdf from 'jspdf'
import 'jspdf-autotable'
import '../assets/pdfFont/SIMHEI.js'
export default {
  components: {
    CommonLoading
  },
  data() {
    return {
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      timeOut: null,
      chatIsList: false,
      chartnames: ['行人入侵数量统计', '违章停车数量统计', '车辆拥堵数量统计', '车流量统计', '路段流量统计', '其他数据统计'],
      chartid: ['people', 'stopping', 'jam', 'count', 'roadflow', 'other'],
      dialogchartid: ['dialogpeople', 'dialogstopping', 'dialogjam', 'dialogcount', 'dialogroadflow', 'dialogother'],
      datakey: ['e_person', 'e_stop', 'e_jam', 'count', 'upcount', 'downcount', 'road_flow', 'e_back', 'e_dc', 'e_slow', 'e_stop'],
      griddata: [],
      loading: false,
      chartData: {
        count: [],
        upcount: [],
        downcount: [], //车流量
        jam: [], //车辆拥堵
        person: [], //行人入侵
        roadflow: [],
        stop: [],
        // bd_vehicle: [],
        e_back: [],
        e_dc: [],
        e_slow: [],
        xaxis: [],
        xname: '',
        datetime: [],
        road: '',
        group: '',
      },
      showchartsPdf: false,
      addressLoading: false,
      address: [],
      groups: [{
        en: 'year',
        ch: '年',
        tip: '显示选择时间段所在年份的统计信息'
      }, {
        en: 'quarter',
        ch: '季度',
        tip: '显示开始时间所在年份的季度统计信息'
      },{
        en: 'month',
        ch: '月',
        tip: '显示开始时间月份至结束时间月份的统计信息,不支持跨年查询'
      },{
        en: 'week',
        ch: '周',
        tip: '显示开始时间至结束时间按周统计的信息,不支持跨年查询'
      }, {
        en: 'day',
        ch: '日',
        tip: '显示开始时间至该月月末的每日统计信息'
      }, {
        en: 'hour',
        ch: '小时',
        tip: '显示开始时间至24时的每小时统计信息'
      }],
      rules: {
        datetime: [
          { required: true, message: '请输入统计时间段', trigger: 'blur' }
        ],
        group: [
          { required: true, message: '请选择统计方式', trigger: 'blur' }
        ]
      },
      images: [],
      text: [],
      imgFlag: false,
      pdf:null,
      color:['#fff','#333'],
      tipforcharts: ''
    };
  },
  computed: {
    getCollapse() {
      return this.$store.state.collapseFlag;
    },
    _chartResize() {
      return _.throttle(() => {
        this.resizeCharts()
      }, 400)
    }
  },
  created(){
    this.defaultData();
  },
  mounted() {
    this.fetchData();
    const _chartDomId = this.chartid
    this.chatIsList = _.isArray(_chartDomId)
    this.initCharts(this.chartid,0)
    window.addEventListener("resize", this._chartResize)
  },
  destroyed() {
    window.removeEventListener("resize", this._chartResize)
    clearTimeout(this.timeOut)
  },
  watch: {
    getCollapse(val) {
      if(this.timeOut) clearTimeout(this.timeOut)
      this.timeOut = setTimeout(()=>{
        this.resizeCharts()
      },200)
    },
    imgFlag(val) {
      if (val)
        this.generatePdf()
    }
  },
  methods: {
    chartWrapperDom(_chartDomId) {
      if (_.isString(_chartDomId)) {
        const dom = document.getElementById(_chartDomId)
        return dom && echarts.init(dom)
      } else if (_.isArray(_chartDomId)) {
        const domList = _chartDomId.map(id => document.getElementById(id))
        return domList && domList.map(dom => echarts.init(dom))
      } else throw new Error('chartDomId 应为 Array 或 String')
    },
    resize(charts){
      if(this.chatIsList){
        this.chartWrapperDom(charts).forEach(chart => chart.resize())
      }else{
        this.chartWrapperDom(charts).resize()
      }
    },
    resizeCharts() {
      this.resize(this.chartid)
      if (this.showchartsPdf == true) {
        this.resize(this.dialogchartid)
      }
    },
    getxAxisName() {
      let data = this.groups
      for (let i in data) {
        if (data[i]['en'] == this.chartData.group)
          return data[i]['ch']
      }
      return ''
    },
    getRoadList() {
      this.addressLoading = true;
      this.$api.statistics.RoadList().then(response => {
        this.addressLoading = false;
        if (response.data.code == "6000") {
          let data = response.data.data;
          this.address.splice(0, this.address.length)
          for (let i in data) {
            this.address.push(data[i]['ch_name'])
          }
        } else {
          this.$message({
            message: util.getErrorInfo(response.data.code),
            type: 'error'
          });
        }
      }).catch(error => {
        this.addressLoading = false;
      });
    },
    setTipforcharts(name,xaxis){
      this.tipforcharts='* 当前查看的是：'
      var rest=''
      var year1=this.chartData.datetime[0].substring(0,4)
      var year2=this.chartData.datetime[1].substring(0,4)
      var mon1=this.chartData.datetime[0].substring(5,7)
      var mon2=this.chartData.datetime[1].substring(5,7)
      var day1=this.chartData.datetime[0].substring(8,10)
      if(name=='年')
      {
        for(let i in xaxis)
          rest=rest+xaxis[i]+' '
        rest=rest+'年的统计信息'
      }else if(name=='季度'){
        rest=this.chartData.datetime[0].substring(0,4) +'年的四个季度统计信息'
      }else if(name=='月'){
        if(year1==year2)
         rest=year1+'年'+mon1+'到'+mon2+'月'+'按月划分的统计信息'
        else
         rest='不支持跨年查询，仅显示开始时间到'+year1+'年'+'12月'+'按月划分的统计信息'
      }else if(name=='周'){
        if(year1==year2)
         rest=this.chartData.datetime[0].substring(0,10)+'至'+this.chartData.datetime[1].substring(0,10)+'按周显示的统计信息'
        else
         rest='不支持跨年查询，仅显示'+this.chartData.datetime[0].substring(0,10)+'至'+year1+'年最后一周按周显示的统计信息' 
      }else if(name=='日'){
        rest=year1+'年'+mon1+'月'+day1+'日至月末的每日数据'
      }else if(name=='小时'){
        rest=year1+'年'+mon1+'月'+day1+'日'+this.chartData.datetime[0].substring(11,13)+'时至24时的每小时数据'
      }
      this.tipforcharts=this.tipforcharts+rest
    },
    handleRoadListFocus(){
      if(this.address.length <= 0) this.getRoadList();
    },
    initData() {
      this.chartData['count'].splice(0, this.chartData['count'].length)
      this.chartData['upcount'].splice(0, this.chartData['upcount'].length)
      this.chartData['downcount'].splice(0, this.chartData['downcount'].length) //车流量
      this.chartData['jam'].splice(0, this.chartData['jam'].length) //车辆拥堵
      this.chartData['person'].splice(0, this.chartData['person'].length) //行人入侵
      this.chartData['roadflow'].splice(0, this.chartData['roadflow'].length)
      this.chartData['stop'].splice(0, this.chartData['stop'].length)
      this.chartData['e_back'].splice(0, this.chartData['e_back'].length)
      this.chartData['e_dc'].splice(0, this.chartData['e_dc'].length)
      this.chartData['e_slow'].splice(0, this.chartData['e_slow'].length)
      this.chartData['xaxis'].splice(0, this.chartData['xaxis'].length)
      this.griddata.splice(0, this.griddata.length)
    },
    processData(data) {
      this.chartData['xname'] = this.getxAxisName();
      this.initData();
      var j = 0;
      for (let i in data) {
        this.griddata.push(data[i])
        this.griddata[j]['index'] = i
        this.chartData['e_back'].push(data[i]["e_back"])
        this.chartData['e_dc'].push(data[i]["e_dc"])
        this.chartData['e_slow'].push(data[i]["e_slow"])
        this.chartData['person'].push(data[i]["e_person"])
        this.chartData['jam'].push(data[i]["e_jam"])
        this.chartData['roadflow'].push(data[i]["road_flow"])
        this.chartData['downcount'].push(data[i]["downcount"])
        this.chartData['upcount'].push(data[i]["upcount"])
        this.chartData['count'].push(data[i]["count"])
        this.chartData['stop'].push(data[i]["e_stop"])
        this.chartData['xaxis'].push(i)
        j++
      }
      this.setTipforcharts( this.chartData['xname'],this.chartData['xaxis'])
      this.initCharts(this.chartid,0);
    },
    fetchData() {
      this.loading = true;
      let params = {
        start_time: this.chartData.datetime[0],
        end_time: this.chartData.datetime[1],
        road_name: this.chartData.road,
        group: this.chartData.group
      };
      this.$api.statistics.trafficStatisticsData(params).then(response => {
        setTimeout(() => { this.loading = false; }, 500);
        if (response.data.code == "6000") {
          let data = response.data.data;
          this.processData(data);
        } else {
          this.$message({
            message: util.getErrorInfo(response.data.code),
            type: 'error'
          });
        }
      }).catch(error => {
        this.loading = false;
      });
    },
    initCharts(chartIdData,colorId) {
      this.initPeopleOption(chartIdData[0],colorId);
      this.initStoppingOption(chartIdData[1],colorId);
      this.initJamOption(chartIdData[2],colorId);
      this.initCountOption(chartIdData[3],colorId);
      this.initRoadflowOption(chartIdData[4],colorId);
      this.initOtherOption(chartIdData[5],colorId);
    },
    initPeopleOption(chartid,colorId) {
      // 基于准备好的dom，初始化echarts实例
      var myChart = echarts.init(document.getElementById(chartid));
      // 指定图表的配置项和数据
      var option = {
        title: {
          show: false
        },
        tooltip: {},
        color: [ '#E67A2F', '#53f09b', '#cf5f67','#00b2ff'],
        legend: {
          data: ['行人入侵个数'],
          padding: 10,
          itemWidth: 18,
          textStyle:{
            color:this.color[colorId]
          }
        },
        xAxis: {
          type: 'category',
          name: this.chartData['xname'],
          data: this.chartData['xaxis'],
          axisLine:{
            lineStyle:{
              color:this.color[colorId]
            }
          }

        },
        grid: {
          left: 50,
          right:40,
          bottom:60
        },

        yAxis: {
          axisLine:{
            lineStyle:{
              color:this.color[colorId]
            }
          },
          axisLabel:{
             formatter: (value)=>this.dealNumber(value)
          },
          splitLine:{
            lineStyle:{
              color:'#B2B2B2'
            }
          }
        },
        series: [{
          name: '行人入侵个数',
          type: 'bar',
          barMaxWidth: '35',
          data: this.chartData['person'],
        }],
        animation:false
      };
      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option);
    },
    initStoppingOption(chartid,colorId) {
      // 基于准备好的dom，初始化echarts实例
      var myChart = echarts.init(document.getElementById(chartid));
      // 指定图表的配置项和数据
      var option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        color: ['#40FBFF', '#cf5f67','#00b2ff','#f2d643'],
        legend: {
          data: ["违章停车"],
          padding: 10,
          itemWidth: 18,
          textStyle:{
            color:this.color[colorId]
          }
        },
        grid: {
          left: 50,
          right:40,
          bottom:60
        },
        xAxis: {
          type: 'category',
          name: this.chartData.xname,
          data: this.chartData.xaxis,
          // boundaryGap: false,
          axisLine:{
            lineStyle:{
              color:this.color[colorId]
            }
          },   
        },
        yAxis: {
          type: 'value',
          axisLine:{
            lineStyle:{
              color:this.color[colorId]
            }
          },
          axisLabel:{
              formatter: (value)=>this.dealNumber(value)
          },
          splitLine:{
            lineStyle:{
              color:'#B2B2B2'
            }
          }
        },
        series: [{
          name: '违章停车',
          type: 'line',
          data: this.chartData.stop,
          symbol: 'circle',
        }],
        animation:false
      };
      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option);
    },
    initJamOption(chartid,colorId) {
      // 基于准备好的dom，初始化echarts实例
      var myChart = echarts.init(document.getElementById(chartid));
      // 指定图表的配置项和数据
      var option = {
        color: [ '#E86343','#00b2ff','#f2d643','#53f09b'],
        legend: {
          data: ['车辆拥堵数量'],
          padding: 10,
          itemWidth: 18,
          textStyle:{
            color:this.color[colorId]
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        xAxis: {
          type: 'category',
          name: this.chartData.xname,
          data: this.chartData.xaxis,
          axisLine:{
            lineStyle:{
              color:this.color[colorId]
            }
          },
        },
        grid: {
          left: 50,
          right:40,
          bottom:60
        },
        yAxis: {
          type: 'value',
          boundaryGap: [0, '100%'],
          axisLine:{
            lineStyle:{
              color:this.color[colorId]
            }
          },
          axisLabel:{
             formatter: (value)=>this.dealNumber(value)
          },
          splitLine:{
            lineStyle:{
              color:'#B2B2B2'
            }
          }
        },
        series: [{
          name: '车辆拥堵数量',
          data: this.chartData.jam,
          type: 'line',
          symbol: 'circle',
        }],
        animation:false
      };

      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option);
    },
    initCountOption(chartid,colorId) {
      // 基于准备好的dom，初始化echarts实例
      var myChart = echarts.init(document.getElementById(chartid));
      var itemStyle = {
        normal: {},
        emphasis: {
          barBorderWidth: 1,
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowOffsetY: 0,
          shadowColor: 'rgba(0,0,0,0.5)'
        }
      };
      // 指定图表的配置项和数据
      var option = {
        tooltip: {
          trigger: 'axis'
        },
        color: ['#9075ED','#CABAEB','#40FBFF','#cf5f67'],
        legend: {
          data: ['上行车流量', '下行车流量', '总车流量'],
          padding: 10,
          itemWidth: 18,
          textStyle:{
            color:this.color[colorId]
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        xAxis: [{
          type: 'category',
          name: this.chartData.xname,
          data: this.chartData.xaxis,
          axisLine:{
            lineStyle:{
              color:this.color[colorId]
            }
          }
        }],
        grid: {
          left: 50,
          right:40,
          bottom:60
        },
        yAxis: [{
          type: 'value',
          axisLine:{
            lineStyle:{
              color:this.color[colorId]
            }
          },
        axisLabel:{
             formatter: (value)=>this.dealNumber(value)
          },
          splitLine:{
            lineStyle:{
              color:'#B2B2B2'
            }
          }
        }],
        series: [{
            name: '上行车流量',
            type: 'bar',
            itemStyle: itemStyle,
            data: this.chartData.upcount,
            barMaxWidth: '35'
          },
          {
            name: '下行车流量',
            type: 'bar',
            itemStyle: itemStyle,
            data: this.chartData.downcount,
            barMaxWidth: '35'
          },
          {
            name: '总车流量',
            type: 'line',
            smooth: true,
            symbol: 'circle',
            itemStyle: itemStyle,
            data: this.chartData.count,

          }
        ],
        animation:false
      };

      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option);
    },
    initRoadflowOption(chartid,colorId) {
      // 基于准备好的dom，初始化echarts实例
      var myChart = echarts.init(document.getElementById(chartid));
      // 指定图表的配置项和数据
      var option = {
        color: [ '#00b2ff','#f2d643','#53f09b','#cf5f67'],
        legend: {
          data: ['路段流量'],
          padding: 10,
          itemWidth: 18,
          textStyle:{
            color:this.color[colorId]
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        xAxis: {
          type: 'category',
          name: this.chartData.xname,
          data: this.chartData.xaxis,
          axisLine:{
            lineStyle:{
              color:this.color[colorId]
            }
          }
        },
        grid: {
          left: 50,
          right:40,
          bottom:60
        },
        yAxis: {
          type: 'value',
          boundaryGap: [0, '100%'],
          axisLine:{
            lineStyle:{
              color:this.color[colorId]
            }
          },
          axisLabel:{
             formatter:(value)=>this.dealNumber(value)
          },
          splitLine:{
            lineStyle:{
              color:'#B2B2B2'
            }
          }
        },
        series: [{
          name: '路段流量',
          data: this.chartData.roadflow,
          type: 'line',
          symbol:'circle'
        }],
        animation:false
      };
      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option);
    },
    initOtherOption(chartid,colorId) {
      var myChart = echarts.init(document.getElementById(chartid));
      var option = {
        title: {
          show: false
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        color: [ '#4DB3A7','#f2d643','#2491C9','#00b2ff'],
        legend: {
          data: [ '逆行车辆', '危险品车辆', '缓行车辆'],
          padding: 10,
          itemWidth: 18,
          textStyle:{
            color:this.color[colorId]
          },
        },
        xAxis: [{
          type: 'category',
          name: this.chartData.xname,
          data: this.chartData.xaxis,
          axisLine:{
            lineStyle:{
              color:this.color[colorId]
            }
          }
        }],
        grid: {
          left: 50,
          right:40,
          bottom:60
        },
        yAxis: [{
          type: 'value',
          nameGap:0,
          axisLine:{
            lineStyle:{
              color:this.color[colorId]
            }
          },axisLabel:{
             formatter: (value)=>this.dealNumber(value)
          },
          splitLine:{
            lineStyle:{
              color:'#B2B2B2'
            }
          }
        }],
        series: [
          {
            name: '逆行车辆',
            type: 'line',
            data: this.chartData.e_back,
            symbol:'circle'
          },
          {
            name: '危险品车辆',
            type: 'line',
            data: this.chartData.e_dc,
            symbol:'circle'
          },
          {
            name: '缓行车辆',
            type: 'line',
            data: this.chartData.e_slow,
            symbol:'circle'
          }
        ],
        animation:false
      };
      myChart.setOption(option);
    },
    defaultData() {
      var date = new Date();
      var year = date.getFullYear();
      var month = date.getMonth()+1;
      var day = date.getDate();
      var predate=new Date();
      predate.setTime(date.getTime() - 3600 * 1000 * 24 * 30);
      var yearpre = predate.getFullYear();
      var monthpre = predate.getMonth()+1;
      monthpre=(Array(2).join('0') + monthpre).slice(-2);  
      month=(Array(2).join('0') + month).slice(-2); 
      var daypre = predate.getDate();
      daypre=(Array(2).join('0') + daypre).slice(-2);
      day=(Array(2).join('0') + day).slice(-2);
      this.chartData.datetime[1] = year+'-'+month+'-'+day+' 00:00:00';
      this.chartData.datetime[0] = yearpre+'-'+monthpre+'-'+daypre+' 00:00:00';
      this.chartData.group = 'month'
    },
    handleClick() {
      this.$refs.chartData.validate((valid) => {
        if (valid)
          this.fetchData();
          
      });
    },
    handleSize(event) {
      let target = event.currentTarget
      let obj = target.parentNode;
      obj = obj.parentNode;
      if (target.className == "el-icon-zoom-in")
        target.className = "el-icon-zoom-out"
      else
        target.className = "el-icon-zoom-in"
      let flag = false;
      if (obj.className == "item")
        obj.className = "one";
      else {
        obj.className = "item";
        flag = true;
      }

      let nodes = document.getElementById("statisticsContent").children;
      var num = nodes.length;
      for (var i = 0; i < num; i++) {
        var id = nodes[i].id
        if (flag == true)
          nodes[i].style.display = ""
        else if (id != obj.id)
          nodes[i].style.display = "none"
      }
      for (let i in this.chartid)
        echarts.getInstanceByDom(document.getElementById(this.chartid[i])).resize();
    },
    openPdf() {
      this.initCharts(this.dialogchartid,1)
      this.images.splice(0, this.images.length)
      this.text.splice(0, this.text.length)
      this.imgFlag = false
      this.loadImage()
    },
    generatePdf() {
      //表格列头
      var columns = [
        { title: this.chartData.xname, dataKey: "index" },
        { title: "行人入侵", dataKey: "e_person" },
        { title: "违章停车", dataKey: "e_stop" },
        { title: "车辆拥堵", dataKey: "e_jam" },
        { title: "总车流量", dataKey: "count" },
        { title: "上行车流量", dataKey: "upcount" },
        { title: "下行车流量", dataKey: "downcount" },
        { title: "路段流量", dataKey: "road_flow" },
        { title: "逆行车辆", dataKey: "e_back" },
        { title: "危险品车辆", dataKey: "e_dc" },
        { title: "缓行车辆", dataKey: "e_slow" },
      ];
      //表格数据
      var rows = this.griddata
      var doc = new jspdf('p', 'pt', 'a4')
      var pdfWidth = 595.28;
      var pdfheight = 841.89;
      doc.addFont('SIMHEI-normal.ttf', 'SIMHEI', 'normal')
      doc.setFont('SIMHEI')
      doc.setFontSize(8)
      doc.text(10, 20, '时间段：' + this.chartData.datetime[0] + '到' + this.chartData.datetime[1] + ',路段：' + this.chartData.road + ',按' + this.chartData.xname + '统计');
      doc.autoTable(columns, rows, {
        styles: { font: "SIMHEI", fontStyle: "normal", overflow: 'linebreak', cellWidth: 'wrap' }, //表格里设置为中文字
        margin: { right: 280, left: 20 },
        tableWidth: 'wrap'
      });
      doc.addPage()
      doc.setFontSize(16)
      var chart=echarts.getInstanceByDom(document.getElementById(this.dialogchartid[0]))
      var width=chart.getWidth()
      var high=chart.getHeight()
      var ratio=Math.min(340/high,535/width)
      var imgw=width*ratio,imgh=high*ratio
      for (var i = 0; i < 6; i++) {
        var height = 40
        if (i % 2 == 0) {
          height = 40
          if (i != 0)
            doc.addPage()
        } else {
          height = pdfheight/2+40
        }
        doc.text(40, height, this.text[i]);
        doc.addImage(this.images[i], 'JPEG', 30, height + 20,imgw,imgh)
      }
       this.pdf=doc
    },
    loadImage() {
      for (var i=0;i<6;i++) {
        var element = document.getElementById(this.dialogchartid[i])
        var chart=echarts.getInstanceByDom(element)
        let img=new Image()
        img.src=chart.getDataURL()
        img.setAttribute("crossOrigin",'Anonymous')
        let text=this.chartnames[i]
        img.onload=()=>{this.compressImage(img,chart.getWidth(),chart.getHeight(),text)}
      }
    },
    compressImage(img,w,h,t){
        var quality = 0.95; // 默认图片质量为0.7  
        //生成canvas  
        var canvas = document.createElement('canvas');  
        var ctx = canvas.getContext('2d');  
        // 创建属性节点  
        canvas.setAttribute("width", w*2);  
        canvas.setAttribute("height", h*2);
        ctx.fillStyle = "#fff";
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        ctx.drawImage(img, 0, 0, w*2, h*2);  
        // quality值越小，所绘制出的图像越模糊  
        var base64 = canvas.toDataURL('image/jpeg', quality);  
        // 回调函数返回base64的值 
        var tx=t
        this.images.push(base64)
        this.text.push(tx)
        if(this.images.length>5)
          this.imgFlag=true
    },
    downloadPDF(){
      this.pdf.save('统计信息图表数据.pdf')
    },
    handleDialogClose(){
      this.imgFlag=false
      this.pdf=null;
      this.showchartsPdf=false;
    },
    dealNumber(value,index){
       let v=parseFloat(value);
              var str='';
              if(v>=10000&&v<1000000){
                var num=v/10000
                num=num.toFixed(1)
                str=num+'万'
                return str
              }
              else if(v>=1000000&&v<10000000){
                var num=v/1000000
                num=num.toFixed(0)
                str=num+'百万'
                return str
              }
              else if(v>=10000000&&v<100000000){
                var num=v/1000000
                num=num.toFixed(0)
                str=num+'千万'
                return str
              }
              else if(v>=100000000){
                var num=v/100000000
                num=num.toFixed(1)
                str=num+'亿'
                return str
              }
              else{
                return value
              }
                
    }
  }
}

</script>
<style lang="scss" scoped>
@import "../assets/basic.scss";
.statisticsContainer {
  height: 100%;
  .statisticsTitle {
    min-height:10%;
    padding: 30px 20px 0px 20px; 
  }
  .statisticsContent {
    height: 79%;
    overflow: hidden;
    .item {
      width: 32%;
      height: 45%;
      margin: 1% 0 0 1%;
      float: left;
      color:#fff;
      background:url("/static/item_bg.png") no-repeat center;
      background-size:100% 100%;
      .title {
        display: flex;
        padding-top: 2%;
        text-align: right;
        font-weight: bold;
        background:url("/static/itemtitle.png") no-repeat center;
        background-size:100% 100%;
      }
      .chartname{
        padding-right:12%;
        font-size:15px;
      }
    }
    .one {
      width: 96%;
      height: 93%;
      margin: 10px 0 0 2%;
      padding-bottom:10px;
      float: left;
      background:url("/static/item_bg.png") no-repeat center;
      background-size:100% 100%;
      color:#fff;
      .title {
        display: flex;
        padding:2%;
        text-align: right;
        font-weight: bold;
        background:url("/static/itemtitle.png") no-repeat center;
        background-size:100% 100%;
        }
        .chartname{
          padding-right: 18%;
          font-size:20px;
      }
    }
    .title {
      display: flex;
      padding: 6%;
      text-align: right;
      font-weight: bold;
    }
    .chart {
      width: 100%;
      height: 90%;
    }
  }
 .pdfcon {
    text-align: center;
  }
  .dialogchart {
    width: 100%;
    height: 100%;
    background-color: #fff;
    text-align: center;
    .dtitle {
      width: 100%;
      height: 100%;
      padding: 20px 0px;
      margin: 10px 0px 0px 0px;
      border-bottom: 1px solid #e8e8e8;
      text-align: center;
      font-weight: bold;
      font-size: 15px;
    }
    .dchart {
      width: 80%;
      height: 400px;
      margin: 0 auto;
    }
  }
  .pdftable {
    background-color:  #fff;
  }

}
</style>
<style lang="css" scoped>
.pdfcon .el-table{
    background-color:  #fff;
}
.pdfcon .el-table >>> th {
      background-color:  #fff ;
      color: #333 ;
    }

.pdfcon .el-table >>> tr {
      background-color:  #fff ;
      color: #333;
    }

.pdfcon .el-table >>> td,
.pdfcon .el-table >>> th.is-leaf {
      border-bottom: 1px solid rgba(0, 0, 0, .2);
    }   
.pdfcon >>> .el-table--border {
    border: 1px solid rgba(0, 0, 0, .2);
}
.pdfcon >>> .el-table--border th, .pdfcon >>> .el-table--border td {
    border-right: 1px solid rgba(0, 0, 0, .2);
}
.pdfcon >>> .el-table__empty-text{
  color:#9fa6b3
}
    
</style>
